﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace BoutiquePOS.DAL.Gateway
{
    public class CodeGenerator : DbGateway
    {
        public string NextID(string query, string firstChar)
        {
            try
            {
                var table = new DataTable();
                string sql = query;
                CommandObj.Parameters.Clear();
                CommandObj.CommandText = sql;
                ConnectionObj.Open();
                SqlDataAdapter ad = new SqlDataAdapter(CommandObj);
                ad.Fill(table);
                string id = table.Rows[0][0].ToString();
                if (id == "")
                {
                    //Sample "CM-000001";
                    string dd = "000001";
                    return firstChar + dd;
                }
                else
                {
                    string temp;
                    int Nonzero;
                    int length;
                    string currentMaxId = table.Rows[0][0].ToString().Trim();
                    string lastSixDigit = currentMaxId.Substring(3,6);
                    temp = lastSixDigit.ToString().Trim();
                    Nonzero = Convert.ToInt32(lastSixDigit.ToString().Trim());
                    int ssss = Nonzero + 1;
                    length = temp.Length - ssss.ToString().Length;
                    string mo = (temp.Substring(0, length) + ssss.ToString());
                    return firstChar + mo;
                }
            }
            catch (Exception exception)
            {
                throw new Exception("Cann't Create Next Id", exception);
            }
            finally
            {
                if (ConnectionObj != null && ConnectionObj.State == ConnectionState.Open)
                {
                    ConnectionObj.Close();
                }
            }
        }

        public string GenerateCustomerCode()
        {
            try
            {
                string firstChar = "CM-";
                string select = "Select max(CustomerCode) From PosCustomer";
                return NextID(select, firstChar);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}